﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Derp.Ver6_3;
using System.Data;
using System.Xml;
using System.Text;
using System.IO;

public partial class ST_SetLogo : CommonFormPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
            bindXmlImgs();
    }
    private string cEnteCode
    {
        get { return getcEnteCode().Substring(0, 4); }
    }
    private string getcEnteCode()
    {
        IDataProxy xmlData = CommonDataProxy.New();
        if (Session["IsPersonID"] != null && Session["IsPersonID"].ToString() != "")
        {
            object obj = xmlData.GetFieldValue(string.Format(@"select cEnteCode from hrPerson where personID={0}", Session["IsPersonID"].ToString()));
            return obj.ToString();
        }
        return "";
    }
    protected void btnSave1_Click(object sender, EventArgs e)
    {
        SaveOption("cLogoImg", this.fileForLogo.PostedFile);
    }
    protected void btnSave2_Click(object sender, EventArgs e)
    {
        SaveOption("cBgImg", this.fileForBg.PostedFile);
    }
    protected void btnSave3_Click(object sender, EventArgs e)
    {
        int index = Convert.ToInt32(this.hd_imgIndex.Value);
        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(this.fileForAd.PostedFile.FileName);
        fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
        string newfileName = Guid.NewGuid().ToString() + fileExtension;
        if (updateXmlByIndex(index, newfileName))
        {
            SaveImage(newfileName, fileForAd.PostedFile);
            bindXmlImgs();
        }
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            updateXmlByIndex(index, "");
            bindXmlImgs();
        }
    }
    private void SaveOption(string feidName, HttpPostedFile postedFile)
    {
        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
        string newfileName = Guid.NewGuid().ToString() + fileExtension;
        if (newfileName != "")
        {
            IDataProxy xmlData = CommonDataProxy.New();
            string sql = "";
            if (isHasImg())
                sql = string.Format("update STHeaderImg set {0}='{1}' where cEnteCode='{2}'", feidName, newfileName, cEnteCode);
            else
                sql = string.Format("insert into STHeaderImg({0},cEnteCode) values('{1}','{2}')", feidName, newfileName, cEnteCode);
            if (xmlData.Execute(sql) > 0)
                SaveImage(newfileName, postedFile);
        }
    }
    private string SaveImage(string newfileName, HttpPostedFile postedFile)
    {
        /**/
        /// '状态信息 
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
        try
        {
            /**/
            ///'检查文件扩展名字 
            string fileName, fileExtension;
            fileName = System.IO.Path.GetFileName(postedFile.FileName);
            if (fileName != "")
            {
                fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
                /**/
                ///'可根据扩展名字的不同保存到不同的文件夹 
                ///注意：可能要修改你的文件夹的匿名写入权限。 
                ///
                if (fileExtension == ".jpg" || fileExtension == ".gif" || fileExtension == ".bmp" || fileExtension == ".png")
                {
                    postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("~/images/uploadimg/") + newfileName);
                    strMsg.Append("<FONT color=#ff0000>图片保存成功！</FONT>");
                }
                else
                {
                    strMsg.Append("<FONT color=#ff0000>图片格式错误，上传的图片必须是jpg或gif或bmp或png格式的</FONT><br><hr>");
                }
            }
        }
        catch (System.Exception Ex)
        {
        }
        strStatus.Text = strMsg.ToString();
        return newfileName;
    }

    private void bindXmlImgs()
    {
        IDataProxy xmlData = CommonDataProxy.New();
        string sql = string.Format("select cAdImg from STHeaderImg where cEnteCode='{0}'", cEnteCode);
        object obj = xmlData.GetFieldValue(sql);
        if (obj != null && obj.ToString() != "")
        {
            string strImgs = obj.ToString();
            DataSet ds = new DataSet();
            StringReader sr = new StringReader(strImgs);
            XmlTextReader xmlReader = new XmlTextReader(sr);
            ds.ReadXml(xmlReader);
            ds.Tables[0].Columns[0].ColumnName = "filename";
            this.Repeater1.DataSource = ds;
            this.Repeater1.DataBind();
        }
    }
    private bool updateXmlByIndex(int i, string value)
    {
        IDataProxy xmlData = CommonDataProxy.New();
        string sql = string.Format("select cAdImg from STHeaderImg where cEnteCode='{0}'", cEnteCode);
        object obj = xmlData.GetFieldValue(sql);
        string strxml = "";
        if (obj != null && obj.ToString() != "")
        {
            string strImgs = obj.ToString();
            XmlDocument xmlImgs = new XmlDocument();
            xmlImgs.LoadXml(strImgs);
            XmlNode root = xmlImgs.SelectSingleNode("imgs");
            if (value != "")
            {
                if (i != -1 && xmlImgs.ChildNodes[0].ChildNodes.Count > i)
                    xmlImgs.ChildNodes[0].ChildNodes[i].InnerText = value;
                else
                {
                    XmlElement xn = xmlImgs.CreateElement("filename");
                    xn.InnerText = value;
                    root.AppendChild(xn);
                }
            }
            else
            {
                root.RemoveChild(root.ChildNodes[i]);
            }
            strxml = xmlImgs.OuterXml;
        }
        else
            strxml = string.Format("<imgs><filename>{0}</filename></imgs>", value);

        int excult = xmlData.Execute(string.Format("update STHeaderImg set cAdImg='{0}' where cEnteCode='{1}'", strxml, cEnteCode));
        return excult > 0;
    }
    public string getimgUrl(string feidName)
    {
        IDataProxy xmlData = CommonDataProxy.New();
        string sql = string.Format("select {0} from STHeaderImg where cEnteCode='{1}'", feidName, cEnteCode);
        object obj = xmlData.GetFieldValue(sql);
        if (obj != null && obj.ToString() != "")
            return "../images/uploadimg/" + obj.ToString();
        return "";
    }
    private bool isHasImg()
    {
        IDataProxy xmlData = CommonDataProxy.New();
        string sql = string.Format("select id from STHeaderImg where cEnteCode='{0}'", cEnteCode);
        return xmlData.GetFieldValue(sql) != null;
    }

    //是否有登录权限
    protected override bool IsEntrySecurity()
    {
        if (Session["IsIdenID"] != null && Session["IsIdenID"].ToString() != "")
            return SecurityPoint.IsEntrySecurity(Session["IsIdenID"].ToString(), "ST_014_SetLogo");
        return false;
    }
}
